<template>
   <div class="home" ref="homeRef">
      <div class="nav-bar">
         <div class="title">宏源旅途</div>
      </div>
      <div class="banner">
         <img src="@/assets/img/home/home-banner.webp" alt="">
      </div>
      <search-box/>
      <category/>
      <content></content>   
      <search-bar v-show="isShowSearchBar"/>
   </div>
</template>

<script setup>
   // 注意，在setup里面是拿不到dom元素的，setup生命周期在beforCreated之前
import { onActivated, onDeactivated, onMounted,onUnmounted,ref, watch } from "vue";
import useScroll from "@/hooks/useScroll"
import SearchBox from "./components/searchBox.vue"
import Category from "./components/categories.vue"
import Content from "./components/content.vue"
import SearchBar from "@/components/searchBar/index.vue"
import useHomeStore from "@/store/modules/home";
import { useRoute } from 'vue-router';

// 发送网络请求
const homeStore = useHomeStore()
homeStore.fetchCategoriesData()
homeStore.fetchHouseList()

// 方式一：回调函数
// useScroll(() => {
//    homeStore.fetchHouseList()
// })

// 方式二：响应式变量
const homeRef = ref()
const {isReachBottom, scrollTop} = useScroll(homeRef)
watch(isReachBottom, (newValue) => {
   // 因为home页面用了keep-alive,因此切换其他页面的时候这里的监听仍然有效。目前是通过document实现滚动，因此切换页面视为滚动又达到了底部，从而发起网络请求
   // 解决办法一：发起网络请求时判断当前路由，网络请求仅对当前路由起作用。
   // 解决办法二：将document滚动转化为盒子滚动。
   // 解决办法三：onUnmounted和onDeactivated时移除滚动功能removeEventListener
   if(newValue){
      homeStore.fetchHouseList().then(() => {
         isReachBottom.value = false
      })
   }
})

// 跳转回到页面时，保留原来的位置（方式是保存scrollTop）
onActivated(() => {
   homeRef.value?.scrollTo({
      top: scrollTop.value
   })
})

const isShowSearchBar = ref(false)
watch(scrollTop, (newTop) => {
   isShowSearchBar.value = newTop > 350
})
</script>

<style lang='less' scoped>
.home{
   height: 100vh;
   overflow-y: auto;
   box-sizing: border-box;
   padding-bottom: 60px;
   // 元素滚动的方案
   // height: calc(100vh - 50px);
   // overflow: auto;
   .title{
      text-align: center;
      color: var(--primary-color);
      font-size: 18px;
      font-weight: 700;
      padding: 10px 0;
   }
   .banner{
      width: 100%;
      height: 150px;
      img{
         width: 100%;
         height: 100%;
      }
   }
}
</style>